<?php

declare(strict_types=1);

namespace App\Controller;

use App\Constants\ErrorCode;
use App\Annotation\EsUp;
use App\Exception\BusinessException;
use App\Model\FlyShop;
use App\Model\LinkChannel;
use App\Model\Product;
use App\Model\Sku;
use App\Service\FlyCartService;
use App\Service\SkuService;
use Hyperf\Validation\Rule;
use Hyperf\DbConnection\Db;
Use Hyperf\Di\Annotation\Inject;
use Psr\Http\Message\ResponseInterface;

class SkuController extends AbstractController
{

    public function list(SkuService $skuService)
    {
        // 关键字：名称
        $product_id = $this->request->input('product_id', '');

        $fields = ['sku_id','sku_name','product_id','single_price','min_quantity','sales_volume','inventory'];
        $where = [];$ids = [];
        if(!$product_id){
            return $this->jsonResponse->error(ErrorCode::SYSTEM_INVALID, '缺少参数');
        }else{
            $where['product_id']=  $product_id;
        }
        $Sku = New Sku();
        $list = [];
        $count = $Sku
            ->where($where)
            ->count();
        if($count>0){
            $list_model = $Sku
                ->where($where)
                ->with(['spec_value','file_info'])
                ->select($fields);
            $list = $this->paginate($list_model);
        }
        return $this->jsonResponse->success($list, '获取列表成功');
    }

    /**
     * @param SkuService $skuService
     * @return ResponseInterface
     * @EsUp(action="add",type=1)
     */
    public function add(SkuService $skuService)
    {
        $params = $this->request->inputs(['product_id','sku','insert_type']);
        $this->validation(
            $params,
            [
                'product_id' => [
                    "required",
                    "integer",
                    Rule::exists('fly_product','id'),
                ],
                'sku' => [
                    "required",
                    "array",
                ],
                'insert_type' => [
                    "required",
                    "min:1",
                    "max:2",
                ],
                'sku.*.sku_name' => [
                    "required",
                    "string",
                    "max:40",
                ],
                'sku.*.inventory' => [
                    "integer",
                    "min:-1",
                ],
                'sku.*.fileinfo_id' => [
                    "integer",
                    Rule::exists('fileinfo','fileinfo_id'),
                ],
                'sku.*.single_price' => [
                    "numeric",
                ],
                'sku.*.min_quantity' => [
                    "integer",
                    "min:1",
                ],
                'sku.*.spec_value' => [
                    "array",
                ],
                'sku.*.spec_value.*.key_id' => [
                    "integer",
                    Rule::exists('fly_product_spec_key','id')->where('product_id',$params['product_id'])
                ],
                'sku.*.spec_value.*.value' => [
                    "string",
                    "max:40",
                ],
                'sku.*.step_price' => [
                    "array",
                    "required",
                ],
                'sku.*.step_price.*.num' => [
                    "integer",
                    "min:1",
                ],
                'sku.*.step_price.*.weight' => [
                    "integer",
                    "min:1",
                ],
                'sku.*.step_price.*.volume' => [
                    "integer",
                    "min:1",
                ],
                'sku.*.step_price.*.price' => [
                    "numeric",
                    "min:0",
                ],

            ],
        );

        Db::beginTransaction();
        $admin_id =  parent::getAdminId();
        $params['created_at'] = date('Y-m-d H:i:s');
        $params['create_by'] = $admin_id;

        try {
            $sku_ids =  $skuService->sku_insert($params['sku'],intval($params['product_id']),intval($params['insert_type']));
            if($sku_ids){
                Db::commit();
                return $this->jsonResponse->success($sku_ids,'添加成功');
            }else{
                Db::rollBack();
                return $this->jsonResponse->error(ErrorCode::SYSTEM_INVALID,'添加失败');
            }
        } catch (\Throwable $exception) {
            Db::rollBack();
            return $this->jsonResponse->error(ErrorCode::SYSTEM_INVALID,'添加失败'.$exception->getMessage());
        }

    }
    /**
     * @param SkuService $skuService
     * @return ResponseInterface
     * @EsUp(action="add",type=1)
     */
    public function edit(SkuService $skuService)
    {
        $params = $this->request->inputs(['product_id','sku','insert_type']);
        $this->validation(
            $params,
            [
                'product_id' => [
                    "required",
                    "integer",
                    Rule::exists('fly_product','id'),
                ],
                'sku' => [
                    "required",
                    "array",
                ],
                'insert_type' => [
                    "required",
                    "min:1",
                    "max:2",
                ],
                'sku.*.sku_id' => [
                    "required",
                    "integer",
                    "min:0",
//                    Rule::exists('fly_sku','sku_id')->whereNull('deleted_at'),
                ],
                'sku.*.sku_name' => [
                    "required",
                    "string",
                    "max:40",
                ],
                'sku.*.inventory' => [
                    "integer",
                    "min:-1",
                ],
                'sku.*.fileinfo_id' => [
                    "integer",
                    Rule::exists('fileinfo','fileinfo_id'),
                ],
                'sku.*.single_price' => [
                    "numeric",
                    "min:0",
                ],
                'sku.*.min_quantity' => [
                    "integer",
                    "min:1",
                ],
                'sku.*.spec_value' => [
                    "array",
                ],
                'sku.*.spec_value.*.key_id' => [
                    "integer",
                    Rule::exists('fly_product_spec_key','id')->where('product_id',$params['product_id'])
                ],
                'sku.*.spec_value.*.value' => [
                    "string",
                    "max:40",
                ],
                'sku.*.step_price' => [
                    "array",
                    "required",
                ],
                'sku.*.step_price.*.num' => [
                    "integer",
                    "min:1",
                ],
                'sku.*.step_price.*.weight' => [
                    "integer",
                    "min:1",
                ],
                'sku.*.step_price.*.volume' => [
                    "integer",
                    "min:1",
                ],
                'sku.*.step_price.*.price' => [
                    "numeric",
                    "min:0",
                ],
            ],
            );
        Db::beginTransaction();
        $admin_id =  parent::getAdminId();
        $params['created_at'] = date('Y-m-d H:i:s');
        $params['create_by'] = $admin_id;
        try {
            $result =  $skuService->sku_update($params['sku'],intval($params['product_id']),intval($params['insert_type']));
            if($result){
                Db::commit();
                return $this->jsonResponse->success([],'修改成功');
            }else{
                Db::rollBack();
                return $this->jsonResponse->error(ErrorCode::SYSTEM_INVALID,'修改失败');
            }
        } catch (\Throwable $exception) {
            Db::rollBack();
            return $this->jsonResponse->error(ErrorCode::SYSTEM_INVALID,'修改失败'.$exception->getMessage());
        }
    }

    /**
     * @param SkuService $skuService
     * @return ResponseInterface
     */
    public function detail(SkuService $skuService)
    {
        $sku_id = $this->request->input('sku_id');
        $this->validation(
            ['sku_id'=>$sku_id],
            [
                'sku_id' => [
                    'required',
                    'string',
                    Rule::exists('fly_sku','sku_id')->whereNull('deleted_at'),
                ],
            ],
        );
        try{
            $info = $skuService->info(intval($sku_id));

            return $this->jsonResponse->success($info,'信息返回');
        } catch (\Throwable $exception) {
            return $this->jsonResponse->error(ErrorCode::SYSTEM_INVALID,'不存在或已删除：'.$exception->getMessage());
        }

    }

    /**
     * @param SkuService $skuService
     * @return ResponseInterface
     * @EsUp(action="add",type=1)
     */
    public function del(SkuService $skuService)
    {
        $ids = $this->request->input('ids');
        $this->validation(
            ['ids'=>$ids],
            [
                'ids' => 'required|array',
                'ids.*' => [
                    'required',
                    'integer',
                    'min:0',
                    Rule::exists('fly_reason_set','id')->whereNull('deleted_at'),
                ],
            ],
            [
                'ids.*.unique'  =>'有关联数据，不可删除',
            ]
        );
        try{
            $skuService->deleteByUser($ids,$this->getAdminId());
            return $this->jsonResponse->success([],'删除成功');
        } catch (\Throwable $exception) {
            return $this->jsonResponse->error(ErrorCode::SYSTEM_INVALID,'删除失败');
        }
    }
}